﻿using Language.Resource;
using Microsoft.Extensions.Localization;
using System;
using System.Linq;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Repository.Interface.Sys;

namespace VisionCloud.Domain.Repository.Implement.Sys
{
    public class SysDeviceUnlockRepository : BaseRepository<SysDeviceUnlock>, ISysDeviceUnlockRepository
    {
        public IStringLocalizer<RepositoryResource> Localizer { get; set; }

        public ApiResult UnlockDevice(SysDeviceUnlockDto unlock)
        {
            var code = Where(c => c.KeyCode == unlock.KeyCode && !c.IsDeleted).FirstOrDefault();
            if (code == null)
                return new ApiResult(Common.AjaxCode.Error, Localizer["YB0266"].Value );
            int seconds = code.Seconds;
            code.IsDeleted = true;
            code.LastUpdatedBy = unlock.UnlockUserGuid;
            code.DeviceGuid = unlock.DeviceGuid;
            code.LastUpdatedDate = DateTime.Now;
            code.UnlockTime = DateTime.Now;
            code.UnlockUserGuid = unlock.UnlockUserGuid;
            code.USBKeyNO = unlock.USBKeyNO;
            code.USBKeyType = unlock.USBKeyType;

            Update(code, false);
            Db.SaveChanges();

            TimeSpan ts = TimeSpan.FromSeconds(seconds);
            return new ApiResult()
            {
                Code = Common.AjaxCode.Success,
                Message = $"{Localizer["YB0267"].Value} {ts.ToString(@"hh\小\时mm\分ss\秒")}",
                Result = new
                {
                    Seconds = seconds
                }
            };
        }
    }
}